package com.xlh.support.training.controller;

import com.xlh.common.Result;
import com.xlh.enums.LocalResourcesEnum;
import com.xlh.exception.common.GlobalException;
import com.xlh.security.UserInfoHolder;
import com.xlh.support.training.domain.Training;
import com.xlh.support.training.domain.TrainingAttr;
import com.xlh.support.training.po.TrainingSavePO;
import com.xlh.support.training.service.TrainingService;
import com.xlh.support.training.vo.TrainingVO;
import com.xlh.vo.IconVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.xlh.support.training.constant.TrainingConstant.SYSTEM_PRESET_CODE;

/**
 * @author cheer
 */
@Api("环境实训管理")
@RestController
@RequestMapping("/training")
public class TrainingController {

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Autowired
    private TrainingService trainingService;

    @ApiOperation("查询实训图标列表")
    @GetMapping("/icon")
    public Result<List<IconVO>> queryImageIcons() {
        List<IconVO> iconVOS = trainingService.listTrainingIcons();
        return Result.success(iconVOS);
    }

    @ApiOperation("查询已发布的环境实训列表")
    @GetMapping
    public Result<List<TrainingVO>> queryPublishedTrainings() {
        List<TrainingAttr> trainingAttrs = trainingService.listPublishedTrainings();

        List<TrainingVO> trainingVOs = new ArrayList<>();
        for (TrainingAttr trainingAttr : trainingAttrs) {
            TrainingVO trainingVO = TrainingVO.builder()
                    .trainingId(trainingAttr.getTrainingId())
                    .trainingName(trainingAttr.getTrainingName())
                    .iconUrl(LocalResourcesEnum.SYSTEM_FILE.getMappingUrl(trainingAttr.getIconUrl()))
                    .trainingSource(Objects.equals(trainingAttr.getTrainingSource(), SYSTEM_PRESET_CODE) ?
                            "系统预置" : trainingAttr.getUsername() != null ? "制作人" + trainingAttr.getUsername() : "教师制作")
                    .description(trainingAttr.getDescription())
                    .build();
            trainingVOs.add(trainingVO);
        }

        return Result.success(trainingVOs);
    }

    @ApiOperation("查询可编辑的环境实训列表")
    @GetMapping("/unpublished")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result<List<TrainingVO>> queryEditableTrainings() {
        List<TrainingAttr> trainingAttrs = trainingService.listEditableTrainings(userInfoHolder.getUserId(),
                userInfoHolder.isTeacher());

        List<TrainingVO> trainingVOs = new ArrayList<>();
        for (TrainingAttr trainingAttr : trainingAttrs) {
            TrainingVO trainingVO = TrainingVO.builder()
                    .trainingId(trainingAttr.getTrainingId())
                    .trainingName(trainingAttr.getTrainingName())
                    .iconUrl(LocalResourcesEnum.SYSTEM_FILE.getMappingUrl(trainingAttr.getIconUrl()))
                    .trainingSource(Objects.equals(trainingAttr.getTrainingSource(), SYSTEM_PRESET_CODE) ?
                            "系统预置" : trainingAttr.getUsername() != null ? "制作人" + trainingAttr.getUsername() : "教师制作")
                    .description(trainingAttr.getDescription())
                    .published(trainingAttr.getPublished())
                    .build();
            trainingVOs.add(trainingVO);
        }

        return Result.success(trainingVOs);
    }

    @ApiOperation("发布环境实训")
    @PostMapping("/publish/{trainingId}")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result publishedTraining(@PathVariable("trainingId") Long trainingId) {
        trainingService.updatePublishStatus(userInfoHolder.getUserId(), trainingId, true);
        return Result.success();
    }

    @ApiOperation("取消发布环境实训")
    @PostMapping("/unpublish/{trainingId}")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result unpublishedTraining(@PathVariable("trainingId") Long trainingId) {
        trainingService.updatePublishStatus(userInfoHolder.getUserId(), trainingId, false);
        return Result.success();
    }

    @ApiOperation("创建环境实训")
    @PostMapping
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result createTraining(@RequestBody @Valid TrainingSavePO trainingSavePO) {
        trainingService.createTraining(trainingSavePO);
        return Result.success();
    }

    @ApiOperation("删除环境实训")
    @DeleteMapping("/{trainingId}")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result deleteTraining(@PathVariable("trainingId") Long trainingId) {
        trainingService.deleteTraining(trainingId);
        return Result.success();
    }

    @ApiOperation("修改环境实训")
    @PutMapping("/{trainingId}")
    @PreAuthorize("@permissionValidator.isAdminOrTeacher()")
    public Result updateTraining(@PathVariable("trainingId") Long trainingId,
                                 @RequestBody @Valid TrainingSavePO trainingSavePO) {
        trainingService.updateTraining(trainingId, trainingSavePO);
        return Result.success();
    }

    @ApiOperation("查询环境实训")
    @GetMapping("/{trainingId}")
    public Result<Training> getTraining(@PathVariable("trainingId") Long trainingId) {
        Training training = trainingService.getTraining(trainingId);
        if (training == null) {
            throw new GlobalException("环境实训不存在");
        }
        return Result.success(training);
    }
}
